//$URL: http://dasding.googlecode.com/svn/branches/spring-security/api/src/main/java/de/piratech/dasding/security/SecurityContextFilter.java $
//$Id: SecurityContextFilter.java 74 2012-10-22 18:17:47Z amuthmann@gmail.com $
package de.piratech.dasding.security;

import javax.ws.rs.ext.Provider;

import org.springframework.stereotype.Component;


import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import com.sun.jersey.spi.container.ResourceFilter;
import de.piratech.dasding.data.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Filter all incoming requests, look for possible session information and use that to create and load a SecurityContext to request.
 *
 * @author "Animesh Kumar <animesh@strumsoft.com>"
 *
 */
@Component   // let spring manage the lifecycle
@Provider    // register as jersey's provider
public class SecurityContextFilter implements ResourceFilter, ContainerRequestFilter {

  @Override
  public ContainerRequest filter(ContainerRequest request) {
    // Get session id from request header
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Object principle = authentication == null ? null : authentication.getPrincipal();
    if (principle != null && principle instanceof User) {
      // Set security context
      request.setSecurityContext(new MySecurityContext((User)principle));
    }
    return request;
  }

  @Override
  public ContainerRequestFilter getRequestFilter() {
    return this;
  }

  @Override
  public ContainerResponseFilter getResponseFilter() {
    return null;
  }
}